
find_program(CARGO_EXECUTABLE
    NAMES cargo
    DOC "Rust cargo executable"
)

if (NOT CARGO_EXECUTABLE)
    message(FATAL_ERROR "Rust cargo executable not found")
else()
    execute_process(
        COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/target
        COMMAND_ECHO STDOUT
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
        RESULT_VARIABLE RUST_GENERATE_RESULT
    )
    if (NOT RUST_GENERATE_RESULT EQUAL 0)
        message(FATAL_ERROR "Failed to generate Rust code")
    endif()

    add_custom_target(hello_rust ALL
        COMMENT "Building Rust plugin:"
        COMMAND
            CARGO_TARGET_NAME=hello_rust
            CARGO_TARGET_DIR=${CMAKE_CURRENT_BINARY_DIR}/target
            CARGO_PLUGIN_DIR=${CMAKE_BINARY_DIR}/plugins 
            ${CARGO_EXECUTABLE} build $<IF:$<STREQUAL:${CMAKE_BUILD_TYPE},Release>,--release,>
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
    )

    # 统一处理不同平台的库文件扩展名
    if(WIN32)
        set(COPY_SUFFIX "dll")
    elseif(APPLE)
        set(COPY_SUFFIX "dylib")
    else()
        set(COPY_SUFFIX "so")
    endif()

    set(COPY_DIR "target/$<IF:$<STREQUAL:${CMAKE_BUILD_TYPE},Release>,release,debug>")

    add_custom_command(TARGET hello_rust 
        POST_BUILD
            COMMENT "Copy hello_rust to plugins:"
            COMMAND ${CMAKE_COMMAND} -E copy ${COPY_DIR}/*.${COPY_SUFFIX} ${CMAKE_BINARY_DIR}/plugins
            WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    )
endif()
